package com.totem.base.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充模型数据
 *
 * @author raymond
 */
@Slf4j
@Component
public class ModelMetaObjectHandler implements MetaObjectHandler {

    /**
     * metaObject是页面传递过来的参数的包装对象，不是从数据库取的持久化对象，因此页面传过来哪些值，metaObject里就有哪些值。
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        Long currentUserId = UserIdContext.getUserId();
        if(currentUserId==null){
            currentUserId = 0L;
        }
        Object createTime = this.getFieldValByName("createTime", metaObject);
        if (null == createTime) {
            this.setFieldValByName("createTime", now, metaObject);
        }
        Object createBy = this.getFieldValByName("createBy", metaObject);
        if (null == createBy) {
            this.setFieldValByName("createBy", currentUserId, metaObject);
        }
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if (null == updateTime) {
            this.setFieldValByName("updateTime", now, metaObject);
        }
        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if (null == updateBy) {
            this.setFieldValByName("updateBy", currentUserId, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date now = new Date();
        Long currentUserId = UserIdContext.getUserId();
        if(currentUserId==null){
            currentUserId = 0L;
        }
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if (null == updateTime) {
            this.setFieldValByName("updateTime", now, metaObject);
        }
        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if (null == updateBy) {
            this.setFieldValByName("updateBy", currentUserId, metaObject);
        }
    }
}
